package com.spic.business.alarm.service.impl;

import com.spic.business.alarm.domain.AlarmWindDamage;
import com.spic.business.alarm.domain.WindDamage;
import com.spic.business.alarm.mapper.AlarmWindDamageMapper;
import com.spic.business.alarm.mapper.WeatherDataMapper;
import com.spic.business.alarm.mapper.WindDamageMapper;
import com.spic.business.alarm.service.DeviceService;
import com.spic.business.alarm.service.WindDamageService;
import com.spic.business.getui.service.PushService;
import com.spic.common.core.constant.SecurityConstants;
import com.spic.common.core.domain.R;
import com.spic.common.core.utils.DateUtils;
import com.spic.common.core.utils.StringUtils;
import com.spic.system.api.RemoteNoticeInfoService;
import com.spic.system.api.RemoteUserService;
import com.spic.system.api.domain.SysNoticeInfo;
import com.spic.system.api.domain.SysUser;
import com.spic.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * WindDamageServiceImpl
 *
 * @author xuxiaochang@chinasofi.com
 * @date 2022/3/17
 */
@Service
public class WindDamageServiceImpl implements WindDamageService
{
    @Autowired
    private WindDamageMapper windDamageMapper;

    @Autowired
    private AlarmWindDamageMapper alarmWindDamageMapper;

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Autowired
    private RemoteNoticeInfoService remoteNoticeInfoService;

    @Autowired
    private WeatherDataMapper weatherDataMapper;

    @Autowired
    private PushService doPush;

    @Autowired
    private DeviceService deviceService;

    @Override
    public List<WindDamage> selectTodayUnfinishedWork(Integer windLevel, String today)
    {
        return windDamageMapper.selectTodayUnfinishedWork(windLevel, today);
    }
    //插入告警信息
    @Override
    public void inserAlarm(List<WindDamage> unfinishedAlarm,Float windRate)
    {
        for (WindDamage windDamage : unfinishedAlarm)
        {
            Date date = new Date();
            String alertDescription = windDamage.getAlertDescription();
            Long workPerson = windDamage.getWorkPerson();
            String serialCode = windDamage.getSerialCode();
            AlarmWindDamage alarmWindDamage = new AlarmWindDamage();
            alarmWindDamage.setAlarmTime(date); //告警时间
            SysUser sysUser = remoteUserService.getUserById(workPerson).getData();
            if(sysUser!=null){
                alarmWindDamage.setPersonName(sysUser.getNickName()); //负责人姓名
                alarmWindDamage.setPhone(sysUser.getPhonenumber()); //负责人电话
            }
            alarmWindDamage.setWorkPerson(workPerson);//负责人id
            alarmWindDamage.setTaskType(windDamage.getTaskType()); //风害类型
            alarmWindDamage.setWindLevelNormal(windDamage.getWindLevelNormal()); //风害级别 告警阈值
            alarmWindDamage.setAlertDescription(alertDescription); //告警描述
            alarmWindDamage.setWorkPlace(windDamage.getWork_place()); //工作地点
            alarmWindDamage.setWindRate(windRate); //风速
            try
            {
                int row = alarmWindDamageMapper.insertAlarm(alarmWindDamage);
                if(row>0){
                    executor.execute(() -> {
                        if(StringUtils.isNotEmpty(workPerson+""))
                        {
                            //推送消息提醒
                            this.noticeInfo(serialCode, workPerson+"", date, alertDescription,windRate);
                        }
                    });
                }
                //插入告警信息 个推和 pc消息

            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }

    @Override
    public List<AlarmWindDamage> selectWindAlarmList(AlarmWindDamage alarmWindDamage)
    {
        return alarmWindDamageMapper.selectAlarmWindDamageList(alarmWindDamage);
    }

    @Override
    public AlarmWindDamage selectWindDamageById(Long id)
    {
        AlarmWindDamage alarmWindDamage = alarmWindDamageMapper.selectAlarmWindDamageById(id);
        return alarmWindDamage;
    }

    /**
     * 通过设备名称获取userId
     * @param deviceName 设备名称
     * @return userId
     */
    public String getUserIdByDeviceName(String deviceName){
        int account = weatherDataMapper.selectAccountByDeviceName(deviceName);
        if(account!=0){
            String userName =  String.format("%08d", account);
            R<LoginUser> loginUser = remoteUserService.getUserInfo(userName, SecurityConstants.INNER);
            if(loginUser!=null && loginUser.getData().getSysUser().getUserId()!=null){
                return loginUser.getData().getSysUser().getUserId().toString();
            }
        }
        return "";
    }

    /**
     * 推送消息
     */
    public void noticeInfo(String deviceName, String userId, Date date,String alertDescription,Float windRate){
        SysNoticeInfo info = new SysNoticeInfo();
        info.setContent("您的检修票工作票编码: "+deviceName+","+alertDescription+",目前风速已达到"+windRate+"级。请勿风害作业,报警时间："+ DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,date));
        info.setTitle("检修票风害告警");
        info.setUserId(userId);
        info.setCreateBy(userId);
        info.setCreateTime(date);
        remoteNoticeInfoService.add(info);
        String cid = remoteUserService.getUserById(new Long(userId)).getData().getCid();
        Integer clientType = remoteUserService.getUserById(new Long(userId)).getData().getClientType();
        if(StringUtils.isNotEmpty(cid)){
            doPush.push(
                    cid,
                    "检修票风害告警","您的检修票工作票编码: "+deviceName+","+alertDescription+",目前风速已达到"+userId+"级。请勿风害作业,报警时间："+ DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,date)
                    ,clientType
            );
        }
    }
}
